package jpa4azure.impl;

import java.util.Iterator;

import com.windowsazure.samples.Property;
import com.windowsazure.samples.table.AzureTableEntity;
import com.windowsazure.samples.table.AzureTableEntityCollection;

public class LazyIterator implements Iterator {

	Iterator<AzureTableEntity> it;
	AzureEntityManager aem;
	Class<?> c;
	Object parent;
	
	public LazyIterator(AzureTableEntityCollection relationships,
			AzureEntityManager aem, Class<?> c, Object parent) {
		it = relationships.iterator();
		this.aem = aem;
		this.c = c;
		this.parent = parent;
	}

	
	public boolean hasNext() {
		// TODO Auto-generated method stub
		return it.hasNext();
	}

	
	public Object next() {
		AzureTableEntity rel = it.next();
		return aem.loadByKey(childPK(rel), childRK(rel), c);
	}
	
	public void remove() {
		AzureTableEntity rel = it.next();
		aem.removeRelationEntity(rel.getPartitionKey(), rel.getRowKey(), parent);
		it.remove();
	}
	
	private String childPK(AzureTableEntity e) {
		for (Property p : e.getProperties()) {
			if (p.getName().equals("childPartitionKey"))
				return p.getRepresentation();
		}
		return null;
	}
	
	private String childRK(AzureTableEntity e) {
		for (Property p : e.getProperties()) {
			if (p.getName().equals("childRowKey"))
				return p.getRepresentation();
		}
		return null;
	}
}
